package com.xiaouyudeguang.common.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DomainUtils {

    final static char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
            '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
            'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
            'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
            'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
            'Z'};

    private static HanyuPinyinOutputFormat hanyuPinyinOutputFormat = null;

    static {
        hanyuPinyinOutputFormat = new HanyuPinyinOutputFormat();
        hanyuPinyinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    }

    public static String getDomain(String str) throws BadHanyuPinyinOutputFormatCombination {
        StringBuilder builder = new StringBuilder();
        char[] charArray = str.toCharArray();
        for (int i = 0; i < Math.min(charArray.length, 4); i++) {
            String[] arr = PinyinHelper.toHanyuPinyinStringArray(charArray[i], hanyuPinyinOutputFormat);
            if (arr != null && arr.length > 0) {
                builder.append(arr[0].toCharArray()[0]);
            }
        }
        return builder.append(RandomUtils.randomId()).substring(0, 7);
    }
}
